package Offer282;

import java.util.ArrayList;
import java.util.List;

/**
 * 给表达式添加运算符:
 * 给定一个仅包含数字 0-9 的字符串 num 和一个目标值整数 target
 * 在 num 的数字之间添加 二元 运算符（不是一元）+、- 或 * ，返回所有能够得到目标值的表达式。
 * @author 23737
 * @time 2021.10.16
 */
public class Test {
    public static void main(String[] args) {
        String s = "123";
        int target = 6;
        System.out.println(new Solution().addOperators(s, target));
    }
}

class Solution {
    public List<String> addOperators(String num, int target) {
        List<String> res = new ArrayList<>();
        if (num == null || num.length() == 0) {
            return res;
        }

        help(num, target, 0, 0, 0, "", res);
        return res;
    }

    private void help(String num, int target, long curRes, long diff, int start, String curExp, List<String> expressions) {
        if (start == num.length() && (long)target == curRes) {
            expressions.add(curExp);
        }

        for (int i = start; i < num.length(); i++) {
            String cur = num.substring(start, i + 1);
            if (cur.length() > 1 && cur.charAt(0) == '0') {
                break;
            }

            if (curExp.length() > 0) {
                help(num, target, curRes + Long.parseLong(cur), Long.parseLong(cur), i + 1, curExp + "+" + cur, expressions);
                help(num, target, curRes - Long.parseLong(cur), -Long.parseLong(cur), i + 1, curExp + "-" + cur, expressions);
                help(num, target, (curRes - diff) + diff * Long.parseLong(cur), diff * Long.parseLong(cur),
                        i + 1, curExp + "*" + cur, expressions);
            } else {
                help(num, target, Long.parseLong(cur), Long.parseLong(cur), i + 1, cur, expressions);
            }
        }
    }
}
